package cn.wolfcode.luowowo.comment.service.impl;

import cn.wolfcode.luowowo.comment.domain.SceneCommentReply;
import cn.wolfcode.luowowo.comment.query.SceneCommentReplyQuery;
import cn.wolfcode.luowowo.comment.repository.ISceneCommentReplyRepository;
import cn.wolfcode.luowowo.comment.service.ISceneCommentReplyService;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * Created by admin on 2019/8/13.
 */
@Service
public class SceneCommentReplyServiceImpl implements ISceneCommentReplyService {

    @Autowired
    private MongoTemplate template;

    @Autowired
    private ISceneCommentReplyRepository repository;


    @Override
    public SceneCommentReply saveOrUpdate(SceneCommentReply comment) {
        if (!StringUtils.hasLength(comment.getId())) {
            comment.setCreateTime(new Date());
        }

        if (comment.getType() == SceneCommentReply.SCENE_COMMENT_TYPE) {
            Optional<SceneCommentReply> optional = repository.findById(comment.getRefComment().getId());
            comment.setRefComment(optional.get());
        }

        repository.insert(comment);
        return comment;
    }


    @Override
    public Page<SceneCommentReply> query(SceneCommentReplyQuery qo) {

        Query query = new Query();
        if (qo.getSceneCommentId() != -1) {
            query.addCriteria(Criteria.where("SceneCommentId").is(qo.getSceneCommentId()));
        }

        long count = template.count(query, SceneCommentReply.class);
        if (count == 0) {
            return Page.empty();
        }

        PageRequest pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(),
                Sort.by(Sort.Direction.ASC, "createTime"));

        query.with(pageable);

        List<SceneCommentReply> list = template.find(query, SceneCommentReply.class);

        return new PageImpl<SceneCommentReply>(list, pageable, count);
    }

}
